/*
 * kylin-os-manager
 *
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "dnscheckthread.h"
#include <QUrl>

DnsCheckThread::DnsCheckThread(QObject *parent) : QObject(parent)
{
    m_checkTool = NWCheckToolLib::getInstance();
    connect(this, &DnsCheckThread::sigCheckIsOver, this, &DnsCheckThread::slotCheckIsOver);
}
void DnsCheckThread::slotDnsCheckStart(InnerNetCheck &checkSettings)
{
    //需要复位的数据
    m_hasDNS = false;
    m_settings.clear();
    m_webSite.clear();
    isContinue = true;
    //需要复位的数据
    m_settings = checkSettings;
    m_hasDNS = m_checkTool->isDNSSet();
    if (m_hasDNS) {
        if (m_settings.isInnerCheck) { //需要获取是否开启内网检测
            if (m_settings.webNum != 0) {
                if (m_settings.webNum == 1) {
                    m_webSite = m_settings.web.at(0);
                    getDNSCheckResult(m_webSite);
                } else {
                    qDebug() << "DnsCheckThread::getCheckResult m_settings.web:" << m_settings.web;
                    getDNSCheckResult(m_settings.web, m_settings.webNum);
                }
            } else { //开启了内网设置，但是没有设置内网网址，就不检查了
                emit sigCheckIsOver(CHECKRESULT::DNS_OK);
            }
        } else {
            m_webSite = "https://www.baidu.com";
            getDNSCheckResult(m_webSite);
        }
    } else {
        emit sigCheckIsOver(CHECKRESULT::NO_DNS);
    }
}
void DnsCheckThread::getDNSCheckResult(const QString &web)
{
    QString tempUrl = "";
    if (web.contains("http") || web.contains("/")) {
        tempUrl = QUrl(web).host();
    } else {
        tempUrl = web;
    }
    qDebug() << "DnsCheckThread::getDNSCheckResult1 tempUrl:" << tempUrl;
    if (tempUrl.isEmpty()) {
        emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
        return;
    }
    m_cmdProc = new QProcess();
    qDebug() << "DnsCheckThread::getDNSCheckResult1 nslookup " << tempUrl;
    connect(m_cmdProc, &QProcess::readyReadStandardOutput, this, &DnsCheckThread::readCmdBashInfo);
    connect(m_cmdProc, &QProcess::readyReadStandardError, this, &DnsCheckThread::slotProcessOccurError);
    m_cmdProc->start("nslookup " + tempUrl);
    qDebug() << "DnsCheckThread::getDNSCheckResult1 m_cmdProc->waitForFinished before";
    bool isFinish = m_cmdProc->waitForFinished();
    qDebug() << "DnsCheckThread::getDNSCheckResult1 m_cmdProc->waitForFinished after";
    if (!isFinish) {
        qWarning() << "DnsCheckThread::getDNSCheckResult1 m_cmdProc isFinish:" << isFinish;
        m_cmdProc->kill();
        emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
    }
    disconnect(m_cmdProc, &QProcess::readyReadStandardOutput, this, &DnsCheckThread::readCmdBashInfo);
    disconnect(m_cmdProc, &QProcess::readyReadStandardError, this, &DnsCheckThread::slotProcessOccurError);
    m_cmdProc = nullptr;
}
void DnsCheckThread::getDNSCheckResult(const QList<QString> &list, int len)
{
    for (int i = 0; i < len; ++i) {
        m_webSite = list.at(i);
        QString tempUrl = "";
        if (m_webSite.contains("http") || m_webSite.contains("/")) {
            tempUrl = QUrl(m_webSite).host();
        } else {
            tempUrl = m_webSite;
        }

        if (tempUrl.isEmpty()) {
            qCritical() << "DnsCheckThread::getDNSCheckResult tempUrl.isEmpty()";
            emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
            return;
        }
        qDebug() << "DnsCheckThread::getDNSCheckResult nslookup " << tempUrl;
        m_cmdProc = new QProcess();
        connect(m_cmdProc, &QProcess::readyReadStandardOutput, this, &DnsCheckThread::readCmdBashInfoMore);
        connect(m_cmdProc, &QProcess::readyReadStandardError, this, &DnsCheckThread::slotProcessOccurError);
        m_cmdProc->start("nslookup " + tempUrl);
        qDebug() << "DnsCheckThread::getDNSCheckResult m_cmdProc->waitForFinished before";
        bool isFinish = m_cmdProc->waitForFinished();
        qDebug() << "DnsCheckThread::getDNSCheckResult m_cmdProc->waitForFinished after";
        if (!isFinish) {
            qWarning() << "DnsCheckThread::getDNSCheckResult m_cmdProc isFinish:" << isFinish;
            m_cmdProc->kill();
            isContinue = false;
            emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
        }
        disconnect(m_cmdProc, &QProcess::readyReadStandardOutput, this, &DnsCheckThread::readCmdBashInfoMore);
        disconnect(m_cmdProc, &QProcess::readyReadStandardError, this, &DnsCheckThread::slotProcessOccurError);
        delete m_cmdProc;
        m_cmdProc = nullptr;
        qDebug() << "DnsCheckThread::getDNSCheckResult isContinue:" << isContinue;
        if (!isContinue) {
            return;
        }
    }
    qDebug() << "DnsCheckThread::getDNSCheckResult DNS_OK";
    emit sigCheckIsOver(CHECKRESULT::DNS_OK);
}
void DnsCheckThread::readCmdBashInfoMore()
{
    qDebug() << "DnsCheckThread::readCmdBashInfoMore thread:" << QThread::currentThreadId();
    QByteArray cmdStdOut = m_cmdProc->readAllStandardOutput();
    qDebug() << "DnsCheckThread::readCmdBashInfoMore nslookup:" << cmdStdOut;
    if (cmdStdOut.isEmpty()) {
        isContinue = false;
        emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
        qWarning() << "DnsCheckThread::readCmdBashInfoMore cmdStdOut is null!";
        return;
    }
    QStringList res = (QString::fromLocal8Bit(cmdStdOut)).split("\n");
    for (auto str : res) {
        if (str.contains("timed out", Qt::CaseInsensitive) || str.contains("can't", Qt::CaseInsensitive)
            || str.contains("error", Qt::CaseInsensitive)) {
            //            m_isOverTime = true;
            //            emit processFinished();
            isContinue = false;
            emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
            qDebug() << "DnsCheckThread::readCmdBashInfoMore DNS_ERR!";
            return;
        } else {
            continue;
        }
    }
    qDebug() << "DnsCheckThread::readCmdBashInfoMore func is over!";
}
void DnsCheckThread::readCmdBashInfo()
{
    qDebug() << "DnsCheckThread::readCmdBashInfo thread:" << QThread::currentThreadId();
    QByteArray cmdStdOut = m_cmdProc->readAllStandardOutput();
    qDebug() << "DnsCheckThread::readCmdBashInfo nslookup:" << cmdStdOut;
    if (cmdStdOut.isEmpty()) {
        emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
        return;
    }
    QStringList res = (QString::fromLocal8Bit(cmdStdOut)).split("\n");
    for (auto str : res) {
        if (str.contains("timed out", Qt::CaseInsensitive) || str.contains("can't", Qt::CaseInsensitive)
            || str.contains("error", Qt::CaseInsensitive)) {
            qDebug() << "DnsCheckThread::readCmdBashInfo DNS_ERR";
            emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
            return;
        } else {
            continue;
        }
    }
    qDebug() << "DnsCheckThread::readCmdBashInfo DNS_OK";
    emit sigCheckIsOver(CHECKRESULT::DNS_OK);
}
void DnsCheckThread::slotProcessOccurError()
{
    qWarning() << "DnsCheckThread::slotProcessOccurError";
    if (m_cmdProc) {
        int exitCode = m_cmdProc->exitCode();
        QByteArray cmdErr = m_cmdProc->readAllStandardError();
        QString errStr = QString::fromLocal8Bit(cmdErr);
        qWarning() << "DnsCheckThread::slotProcessOccurError exitCode:" << exitCode;
        qWarning() << "DnsCheckThread::slotProcessOccurError errStr:" << errStr;
        isContinue = false;
        emit sigCheckIsOver(CHECKRESULT::DNS_ERR);
    }
}
void DnsCheckThread::slotCheckIsOver(CHECKRESULT result)
{
    qDebug() << "DnsCheckThread::slotCheckIsOver currentThread:" << QThread::currentThreadId();
    if (result == CHECKRESULT::NO_DNS) {
        m_cur.setCurInfo(tr("NO DNS"), tr("ERR"));
        m_cur.setStatusCheck(CheckStatus::ERROR);
    } else if (result == CHECKRESULT::DNS_ERR) {
        if (m_settings.isInnerCheck) {
            m_cur.setCurInfo(tr("INNER NET RESOLVE TIME OUT"), tr("ERR"));
            m_cur.setStatusCheck(CheckStatus::ERROR);
        } else {
            m_cur.setCurInfo(tr("HAS DNS,TIME OUT"), tr("ERR"));
            m_cur.setStatusCheck(CheckStatus::ERROR);
        }
    } else if (result == CHECKRESULT::DNS_OK) {
        m_cur.setCurInfo(tr("HAS DNS,CONNECTED"), tr("OK"));
        m_cur.setStatusCheck(CheckStatus::EVERTHING_IS_OK);
    }
    emit sigDnsCheckIsOver(m_cur);
}
